import React, { useEffect, useRef } from "react";
import styled from "styled-components";
import Card from "@mui/material/Card";
import * as echarts from "echarts";
import { setBarChartOpt } from "./barChartOpt";
import { connect } from "react-redux";
import { parseToRecordMonth } from "redux/reducers/recordList";
import { setLineChartOpt } from "./lineChartOpt";
import { padding } from "@mui/system";
const StatisticWrapper = styled.div`
  .chart {
    height: 200px;
  }
`;

const MonthChartList = (props: any) => {
  const initChart = (
    divRef: HTMLElement,
    data: monthDataType[],
    title: string
  ) => {
    const _chart = echarts.init(divRef);
    const _opt = setLineChartOpt(data, title);
    _opt && _chart.setOption(_opt);
  };
  const outputRef = useRef(null);
  const inputRef = useRef(null);
  let inputData: monthDataType[] = [];
  let outputData: monthDataType[] = [];
  const records = props.records;

  //-----------------------
  const initData = (data: RecordType[], type: number) => {
    const monthRecords = parseToRecordMonth(records);
    return monthRecords.children.map((child) => {
      return {
        key: child.dayOfMonth,
        value: type === 0 ? child.output : child.input,
      };
    });
  };

  outputData = initData(records, 0);
  inputData = initData(records, 1);
  useEffect(() => {
    initChart(outputRef.current!, outputData, "本月支出");
    initChart(inputRef.current!, inputData, "本月收入");
  });
  return (
    <StatisticWrapper>
      <Card sx={{ margin: "10px 10px" ,padding: "8px"}}>
        <div ref={outputRef} className="chart"></div>
      </Card>
      <Card sx={{ margin: "10px 10px",padding: "8px" }}>
        <div ref={inputRef} className="chart"></div>
      </Card>
    </StatisticWrapper>
  );
};
const mapStateToProps = (state: any) => {
  return { records: state.record };
};
export default connect(mapStateToProps)(MonthChartList);
